// useCurrentTime.js
import { ref, onMounted, onUnmounted } from 'vue'

export function useCurrentTime() {
    const currentTime = ref('')

    const formatTime = (date) => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')

        return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
    }

    const updateCurrentTime = () => {
        currentTime.value = formatTime(new Date())
    }

    let timer = null

    const startTimer = () => {
        updateCurrentTime() // 立即更新一次时间
        timer = setInterval(updateCurrentTime, 1000)
    }

    const stopTimer = () => {
        if (timer) {
            clearInterval(timer)
            timer = null
        }
    }

    // 在组件中使用时自动启动和清理定时器
    onMounted(() => {
        startTimer()
    })

    onUnmounted(() => {
        stopTimer()
    })

    return {
        currentTime,
        startTimer,
        stopTimer
    }
}
